<?php
class ValidateCode {
	private $codelen=4;
	private $width=130;
	private $height=50;
	private $fontsize=20;
	private $font = './ELEPHNT.TTF';
	private $img;
	private $code;

	public function __construct(){}
	private function createCode(){
		$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		$_leng = strlen($charset)-1;
		$code = '';
		for( $i=1; $i<=$this->codelen; $i++ ){
			$code .= $charset[mt_rand(0,$_leng)];
		}
		return $code;
	}

	private function createBg(){
		$this->img = imagecreatetruecolor( $this->width, $this->height );
		$color = imagecolorallocate( $this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255) );
		imagefilledrectangle( $this->img, 0, $this->height, $this->width, 0, $color );
	}

	private function createFont( $code ){
		$_x=( $this->width / $this->codelen );
		for ($i=0;$i<$this->codelen;$i++){
			$color = imagecolorallocate( $this->img, mt_rand(0,156), mt_rand(0,156), mt_rand(0,156) );
			imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height/1.4,$color,$this->font,$code[$i]);
		}
	}
	private function createLine(){
		for ($i=0;$i<6;$i++){
			$color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
			imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
		}
		for ($i=0;$i<45;$i++){
			$color = imagecolorallocate($this->img,mt_rand(220,255),mt_rand(220,255),mt_rand(220,255));
			imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
		}
	}

	private function outPut($show){
		$name = 'code.png';
		if($show){
			header('Content-type:image/png');
			imagepng($this->img);
		}else{
			imagepng($this->img,$name);
		}
		imagedestroy($this->img);
		return $name;
	}
	public function getImg($show=false){
		$this->createBg();
		$code = $this->createCode();
		$this->createLine();
		$this->createFont( $code );
		$this->code = $code;
		return $this->outPut($show);
	}

	public function getString(){
		return strtolower($this->code);
	}
}

$img=new ValidateCode();
if( isset($_REQUEST['path']) && $_REQUEST['path'] ){
	echo $img->getImg();
}else{
	$img->getImg(true);
}
